package com.tbl.modules.wms2.service.impl.ordermanage.asn;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tbl.common.utils.PageTbl;
import com.tbl.common.utils.PageUtils;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.wms2.common.Utils;
import com.tbl.modules.wms2.dao.ordermanage.asn.AsnHeaderDAO;
import com.tbl.modules.wms2.dao.ordermanage.asn.AsnLineDAO;
import com.tbl.modules.wms2.dao.purchasein.PurchaseOrderDAO;
import com.tbl.modules.wms2.entity.operation.YclInOutFlowEntity;
import com.tbl.modules.wms2.entity.ordermanage.asn.*;
import com.tbl.modules.wms2.entity.ordermanage.delivery.DeliveryEntity;
import com.tbl.modules.wms2.service.common.CountService;
import com.tbl.modules.wms2.service.operation.YclInOutFlowService;
import com.tbl.modules.wms2.service.ordermanage.asn.AsnHeaderService;
import com.tbl.modules.wms2.service.ordermanage.asn.AsnLineService;
import com.tbl.modules.wms2.service.ordermanage.delivery.DeliveryService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author DASH
 */
@Service("yclAsnHeaderService")
public class AsnHeaderServiceImpl extends ServiceImpl<AsnHeaderDAO, AsnHeaderEntity> implements AsnHeaderService {

    @Resource
    private AsnHeaderDAO asnHeaderDAO;

    @Resource
    private AsnLineDAO asnLineDAO;

    @Resource
    private PurchaseOrderDAO purchaseOrderDAO;

    @Resource
    private CountService countService;

    @Resource
    private DeliveryService deliveryService;

    @Resource
    private YclInOutFlowService yclInOutFlowService;

    @Resource
    private AsnLineService asnLineService;

    @Override
    public List<AsnVO> listViewAsn(AsnQueryDTO asnQueryDTO) {

        return asnHeaderDAO.listViewAsn(asnQueryDTO);
    }

    @Override
    public Long getSequence() {
        return asnHeaderDAO.getSequence();
    }

    /**
     * 新增送退货货单（头数据和行数据）
     *
     * @param asn
     * @return
     */
    @Override
    @Transactional
    public Boolean insertAsn(AsnCreateDTO asn) {
        if (asn.getAsnLines() == null || asn.getAsnLines().size() < 1) {
            return false;
        }
        AsnHeaderEntity asnHeaderEntity = asn.getAsnHeader();
        // 头数据
        asnHeaderEntity.setDataSource("WMS");
        if ("1".equals(asnHeaderEntity.getAsnType())) {
            asnHeaderEntity.setAsnNumber(countService.getNextCount("SHD"));
        } else {
            asnHeaderEntity.setAsnNumber(countService.getNextCount("THD"));
        }
        asnHeaderEntity.setCreationDate(DateUtil.date());
        int result = asnHeaderDAO.insert(asnHeaderEntity);

        String asnHeaderId = asnHeaderEntity.getAsnHeaderId();
        String vendorCode = null;
        if (asnHeaderDAO.vendorCodeById(String.valueOf(asnHeaderEntity.getVendorId())) != null) {
            vendorCode = asnHeaderDAO.vendorCodeById(String.valueOf(asnHeaderEntity.getVendorId()));
        }

        String jsb = countService.getNextCount("JSB");

        int a = 0;
        // 行数据
        List<AsnLineEntity> asnLines = asn.getAsnLines();
        for (int i = 0; i < asnLines.size(); i++) {
            AsnLineEntity asnLineEntity = asnLines.get(i);
            asnLineEntity.setAsnHeaderId(asnHeaderId);
            asnLineEntity.setLotsNumYd("L" + asnLineEntity.getMaterialCode() + asnLineEntity.getPoCode() + vendorCode + asnLineEntity.getLotsNum());
            asnLineEntity.setStatus("0");
            int lineResult = asnLineDAO.insert(asnLineEntity);


            for (AsnLineEntity item : asnLines) {
                if (asnLineEntity.getLotsNum().equals(item.getLotsNum())) {
                    a++;
                }
            }

            // 送货单
            if ("1".equals(asnHeaderEntity.getAsnType())) {
                // 保存收货表
                DeliveryEntity deliveryEntity = new DeliveryEntity();
                BeanUtils.copyProperties(asnLineEntity, deliveryEntity);
                deliveryEntity.setDeliveryNo(jsb);
                deliveryEntity.setDeliveryLineNo(String.valueOf(i + 1));
                deliveryEntity.setType("1");
                deliveryEntity.setAsnNumber(asnHeaderEntity.getAsnNumber());
                deliveryEntity.setIsPass("0");
                deliveryEntity.setEntityId(String.valueOf(asnHeaderEntity.getPurchaseOrganId()));
                deliveryEntity.setVendorName(asnHeaderEntity.getVendorName());
                deliveryEntity.setVendorCode(asnHeaderEntity.getVendorCode());
                deliveryService.add(deliveryEntity, a == 1);

            }
            if (lineResult < 1) {
                return false;
            }
            a = 0;
        }
        return result == 1;
    }

    @Override
    public void updateAsnHeader(AsnHeaderEntity asnHeaderEntity) {
        asnHeaderDAO.updateAsnHeader(asnHeaderEntity);
    }

    @Override
    public List<AsnHeaderPoVo> listViewHeader(String poCode, String poLineNum) {
        List<AsnHeaderPoVo> list = new ArrayList<>();
        List<String> asnHeaderIds = asnHeaderDAO.getAsnHeaderIds(poCode, poLineNum);
        if (asnHeaderIds.size() > 0) {
            list = asnHeaderDAO.getAsnHeaders(asnHeaderIds.stream().map(String::valueOf).collect(Collectors.joining(",")));
        }
        return list;
    }

    @Override
    public List<AsnHeaderVo> listViewHeader(AsnHeaderQueryDTO asnHeaderQueryVo) {
        return asnHeaderDAO.getAsnHeader(asnHeaderQueryVo);
    }

    @Override
    public List<Map<String, Object>> listViewAsnSelect(AsnQueryDTO asnQueryDTO) {
        List<Map<String, Object>> list = new ArrayList<>();

        YclInOutFlowEntity yclInOutFlowEntity = new YclInOutFlowEntity();
        yclInOutFlowEntity.setBusinessCode(asnQueryDTO.getAsnNumber());
        List<YclInOutFlowEntity> yclInOutFlowEntities = yclInOutFlowService.listView(yclInOutFlowEntity);
        // 有上架记录
        if (yclInOutFlowEntities.size() > 0) {
            for (YclInOutFlowEntity item : yclInOutFlowEntities) {
                Map<String, Object> stringObjectMap = Utils.objectToMap(item);
                stringObjectMap.put("status", "1");
                stringObjectMap.put("deliverQuantity", item.getUpdownQuantity());
                stringObjectMap.put("isInOutData", "1");
                list.add(stringObjectMap);
            }
        } else {
            List<AsnVO> asnVOS = asnHeaderDAO.listViewAsn(asnQueryDTO);
            for (AsnVO item : asnVOS) {
                Map<String, Object> stringObjectMap = Utils.objectToMap(item);
                stringObjectMap.put("isInOutData", "0");
                list.add(stringObjectMap);
            }
        }
        return list;
    }

    /*****************************************************************************/

    @Override
    public Boolean saveSC(AsnCreateDTO asn) {

        if (asn.getAsnLines() == null || asn.getAsnLines().size() < 1) {
            return false;
        }
        AsnHeaderEntity asnHeaderEntity = asn.getAsnHeader();
        // 头数据
        asnHeaderEntity.setDataSource("WMS");
        if ("1".equals(asnHeaderEntity.getAsnType())) {
            asnHeaderEntity.setAsnNumber(countService.getNextCount("SHD"));
        } else {
            asnHeaderEntity.setAsnNumber(countService.getNextCount("THD"));
        }
        asnHeaderEntity.setCreationDate(DateUtil.date());
        int result = asnHeaderDAO.insert(asnHeaderEntity);

        String asnHeaderId = asnHeaderEntity.getAsnHeaderId();

        // 行数据
        List<AsnLineEntity> asnLines = asn.getAsnLines();
        for (int i = 0; i < asnLines.size(); i++) {
            AsnLineEntity asnLineEntity = asnLines.get(i);
            asnLineEntity.setAsnHeaderId(asnHeaderId);
            asnLineEntity.setLotsNumYd(asnLineEntity.getMaterialCode() + asnLineEntity.getLotsNum());
            asnLineEntity.setStatus("0");
            int lineResult = asnLineDAO.insert(asnLineEntity);

            if (lineResult < 1) {
                return false;
            }
        }
        return result == 1;

    }

    @Override
    public Boolean rejectLine(String asnLineId) {

        AsnLineEntity asnLineEntity = asnLineService.selectById(asnLineId);

        DeliveryEntity deliveryEntity = new DeliveryEntity();
        deliveryEntity.setMaterialCode(asnLineEntity.getMaterialCode());
        deliveryEntity.setLotsNum(asnLineEntity.getLotsNum());
        deliveryEntity.setPoCode(asnLineEntity.getPoCode());
        deliveryEntity.setPoLineNum(asnLineEntity.getPoLineNum());
        DeliveryEntity deliveryServiceOne = deliveryService.getOne(deliveryEntity);
        if (deliveryServiceOne != null) {
            deliveryService.delete(deliveryServiceOne.getID());
        }
        asnLineService.deleteById(asnLineEntity.getAsnLineId());

        AsnHeaderQueryDTO asnHeaderQueryDTO = new AsnHeaderQueryDTO();
        asnHeaderQueryDTO.setAsnNumber(asnLineEntity.getAsnHeaderId());
        if (asnHeaderDAO.getAsnHeader(asnHeaderQueryDTO).size() == 0) {
            this.deleteById(asnLineEntity.getAsnHeaderId());
        }

        return true;
    }

    @Override
    public Boolean saveTHSC(List<AsnCreateDTO> asnCreateDTOS) {

        Boolean result = true;

        for (AsnCreateDTO asn : asnCreateDTOS) {

            if (asn.getAsnLines() == null || asn.getAsnLines().size() < 1) {
                return false;
            }
            AsnHeaderEntity asnHeaderEntity = asn.getAsnHeader();
            // 头数据
            asnHeaderEntity.setDataSource("WMS");
            if ("1".equals(asnHeaderEntity.getAsnType())) {
                asnHeaderEntity.setAsnNumber(countService.getNextCount("SHD"));
            } else {
                asnHeaderEntity.setAsnNumber(countService.getNextCount("THD"));
            }
            asnHeaderEntity.setCreationDate(DateUtil.date());
            Integer insert = asnHeaderDAO.insert(asnHeaderEntity);
            if (insert < 1) {
                result = false;
            }

            String asnHeaderId = asnHeaderEntity.getAsnHeaderId();

            // 行数据
            List<AsnLineEntity> asnLines = asn.getAsnLines();
            for (int i = 0; i < asnLines.size(); i++) {
                AsnLineEntity asnLineEntity = asnLines.get(i);
                asnLineEntity.setAsnHeaderId(asnHeaderId);
                asnLineEntity.setLotsNumYd(asnLineEntity.getMaterialCode() + asnLineEntity.getLotsNum());
                asnLineEntity.setStatus("0");
                Integer lineResult = asnLineDAO.insert(asnLineEntity);

                if (lineResult < 1) {
                    result = false;
                }
            }
        }
        return result;

    }


}